package yzy.ecps.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import yzy.ecps.model.BtcBrand;
import yzy.ecps.model.BtcFeature;
import yzy.ecps.model.BtcGoods;
import yzy.ecps.model.BtcSku;
import yzy.ecps.query.condition.PortalGoodsCondition;
import yzy.ecps.service.BrandService;
import yzy.ecps.service.FeatureService;
import yzy.ecps.service.GoodsService;
import yzy.ecps.service.SkuService;
import yzy.ecps.utils.EcpsUtils;
import yzy.ecps.utils.PageInfo;

@Controller
@RequestMapping("/item")
public class GoodsController {
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private BrandService brandService;
	@Autowired
	private FeatureService featureService;
	@Autowired
	private SkuService skuService;
	
	/**
	 * 前台首页
	 * @return
	 */
	@RequestMapping("/index.do")
	public String index(Model model){
		List<BtcBrand> bList = brandService.findAll();
		List<BtcFeature> fList = featureService.findSelectByCatgoryId(1001L);
		model.addAttribute("bList", bList);
		model.addAttribute("fList", fList);
		return "index";
	}
	
	/**
	 * 商品列表页
	 * @param price
	 * @param brandId
	 * @param paraStr
	 * @param model
	 * @return
	 */
	@RequestMapping("/listItem.do")
	public String listGoods(String price,Long brandId,String paraStr,Model model){
		
		PortalGoodsCondition pgc = new PortalGoodsCondition();
		if(price != null && !price.trim().equals("")){
			String[] ps = price.split("-");
			pgc.setMinPrice(new BigDecimal(ps[0]));
			pgc.setMaxPrice(new BigDecimal(ps[1]));
		}
		if(paraStr != null && !paraStr.trim().equals("")){
			pgc.setParaValues(paraStr.split(","));
		}
		
		pgc.setBrandId(brandId);
		
		PageInfo page = goodsService.getPageForPortal(pgc);
		
		model.addAttribute("page", page);
		return "phoneClassification";
	}
	
	/**
	 * 展示 商品信息页面
	 * @param goodsId
	 * @param model
	 * @return
	 */
	@RequestMapping("/showDeatil.do")
	public String showDetail(Long goodsId,Model model){
		BtcGoods goods = goodsService.getGoodsInfo(goodsId);
		model.addAttribute("item", goods);
		return "productDetail";
	}
	
	/**
	 * 获取sku用于查询价格和库存数据
	 * @param skuId
	 * @param response
	 */
	@RequestMapping("/getSkuById.do")
	public void ajax_findSkuById(Long skuId,HttpServletResponse response){
		BtcSku sku = skuService.getById(skuId);
		JSONObject json = new JSONObject();
		json.accumulate("sku", sku);
		String result = json.toString();
		EcpsUtils.printResultForUTF8(result, response);
	}
}
